<template>
  <div class="app-container">
    <el-row class="search">
      <el-select v-model="query.t" style="margin-right: 8px; width: 120px" placeholder="日期类型">
        <el-option v-for="item in [
          { label: '入院日期', value: '入院日期' },
          { label: '出院日期', value: '出院日期' },
        ]" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>

      <el-date-picker v-model="query.stime" style="width: 150px" type="date" placeholder="开始" value-format="yyyy-MM-dd">
      </el-date-picker>
      <span>-</span>
      <el-date-picker style="width: 150px" v-model="query.etime" type="date" placeholder="结束" value-format="yyyy-MM-dd">
      </el-date-picker>

      <!-- <el-select
        v-model="grp"
        multiple
        collapse-tags
        style="margin-left: 8px; width: 120px"
        placeholder="分组"
        @change="grpChange"
      >
        <el-option
          v-for="item in [
            { label: 'DRG组', value: '分组编码,分组名称' },
            { label: 'MDC', value: 'MDC专业,MDC中文名称' },
            { label: '科室', value: '科室' },
            { label: '医生', value: '医生' },
          ]"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select> -->

      <el-select v-model="query.deptValue" style="margin-right: 8px; margin-left: 8px; width: 120px" placeholder="科室">
        <el-option v-for="item in deptLs" :key="item.value" :label="item.text" :value="item.value">
        </el-option>
      </el-select>

      <el-select v-model="query.size" style="margin-right: 8px; width: 120px" placeholder="TOPN">
        <el-option v-for="item in [
          { label: '排名前5', value: '5' },
          { label: '排名前10', value: '10' },
          { label: '排名前20', value: '20' },
          { label: '排名前30', value: '30' },
          { label: '排名前50', value: '50' },
          { label: '排名前100', value: '100' },
          { label: '排名前200', value: '200' },
          { label: '排名前500', value: '500' },
          { label: '排名前1000', value: '1000' },
        ]" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>

      <span style="margin-left: 5px">按</span>
      <el-select v-model="query.o" style="margin-right: 8px; width: 120px" placeholder="排序">
        <el-option v-for="item in [
          { label: '病例数', value: '病例数' },
          { label: '总费用', value: '总费用' },
          { label: '标杆总费用', value: '标杆总费用' },
          { label: 'CMI', value: 'CMI' },
          { label: '时间消耗', value: '时间消耗' },
          { label: '费用消耗', value: '费用消耗' },
        ]" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>

      <el-select v-model="query.x" style="margin-right: 8px; width: 120px" placeholder="排序">
        <el-option v-for="item in [
          { label: '降序', value: 'DESC' },
          { label: '升序', value: 'ASC' },
        ]" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>

      <el-input v-model="query.s" prefix-icon="el-icon-search" style="width: 150px" :placeholder="searchText"
        @keyup.enter.native="search"></el-input>

      <el-button type="warning" style="margin-left: 8px" @click="search" round>搜&nbsp;&nbsp;索</el-button>

      <el-button type="warning" style="margin-left: 8px" v-if="grpIndex != 0" @click="goBack" round>《返回</el-button>
    </el-row>

    <el-row>
      <h5 style="height: 30px; line-height: 30px; margin: 3px; color: red" v-if="navText">
        {{ navText }}
      </h5>
    </el-row>
    <el-row>
      <el-table :data="ls" style="width: 100%" v-loading="isLoading" @row-dblclick="row_dblclick" highlight-current-row
        :summary-method="getSummaries" :show-summary="grpIndex != 0">
        <el-table-column v-for="item in cols" :key="item" :label="item" :prop="item" fixed show-overflow-tooltip>
        </el-table-column>

        <el-table-column prop="病例数" label="病例数"> </el-table-column>
        <el-table-column label="平均总费用">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="比例(scope.row.标杆总费用, scope.row.病例数)" placement="right">
              <span v-bind:class="{
                ffred: IsRed(scope.row.总费用, scope.row.标杆总费用),
                ffblue: IsBlue(scope.row.总费用, scope.row.标杆总费用),
              }">{{ 比例(scope.row.总费用, scope.row.病例数) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column label="平均床日">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="比例(scope.row.标杆床日, scope.row.病例数)" placement="right">
              <span v-bind:class="{
                ffred: IsRed(scope.row.床日, scope.row.标杆床日),
                ffblue: IsBlue(scope.row.床日, scope.row.标杆床日),
              }">{{ 比例(scope.row.床日, scope.row.病例数) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="rw" label="权重"> </el-table-column>
        <el-table-column label="药品消耗">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="
              比例(scope.row.药品费, scope.row.病例数) +
              '/' +
              比例(scope.row.标杆药品费, scope.row.病例数)
            " placement="right">
              <span v-bind:class="{
                ffred: IsRed(scope.row.药品费, scope.row.标杆药品费),
                ffblue: IsBlue(scope.row.药品费, scope.row.标杆药品费),
              }">{{ 比例(scope.row.药品费, scope.row.标杆药品费) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column label="检验消耗">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="
              比例(scope.row.检验费, scope.row.病例数) +
              '/' +
              比例(scope.row.标杆检验费, scope.row.病例数)
            " placement="right">
              <span v-bind:class="{
                ffred: IsRed(scope.row.检验费, scope.row.标杆检验费),
                ffblue: IsBlue(scope.row.检验费, scope.row.标杆检验费),
              }">{{ 比例(scope.row.检验费, scope.row.标杆检验费) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column label="检查消耗">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="
              比例(scope.row.检查费, scope.row.病例数) +
              '/' +
              比例(scope.row.标杆检查费, scope.row.病例数)
            " placement="right">
              <span v-bind:class="{
                ffblue: IsBlue(scope.row.检查费, scope.row.标杆检查费),
                ffred: IsRed(scope.row.检查费, scope.row.标杆检查费),
              }">{{ 比例(scope.row.检查费, scope.row.标杆检查费) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column label="治疗消耗">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="
              比例(scope.row.治疗费, scope.row.病例数) +
              '/' +
              比例(scope.row.标杆治疗费, scope.row.病例数)
            " placement="right">
              <span v-bind:class="{
                ffblue: IsBlue(scope.row.治疗费, scope.row.标杆治疗费),
              }">{{ 比例(scope.row.治疗费, scope.row.标杆治疗费) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column label="耗材消耗">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="
              比例(scope.row.耗材费, scope.row.病例数) +
              '/' +
              比例(scope.row.标杆耗材费, scope.row.病例数)
            " placement="right">
              <span v-bind:class="{
                ffred: IsRed(scope.row.耗材费, scope.row.标杆耗材费),
                ffblue: IsBlue(scope.row.耗材费, scope.row.标杆耗材费),
              }">{{ 比例(scope.row.耗材费, scope.row.标杆耗材费) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column label="手术消耗">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="
              比例(scope.row.手术费, scope.row.病例数) +
              '/' +
              比例(scope.row.标杆手术费, scope.row.病例数)
            " placement="right">
              <span v-bind:class="{
                ffred: IsRed(scope.row.手术费, scope.row.标杆手术费),
                ffblue: IsBlue(scope.row.手术费, scope.row.标杆手术费),
              }">{{ 比例(scope.row.手术费, scope.row.标杆手术费) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>

        <!-- <el-table-column label="CMI">
          <template slot-scope="scope">
            <span v-bind:class="{
              ffred: IsRed(scope.row.CMI, 1),
              ffblue: IsBlue(scope.row.CMI, 1),
            }">{{ scope.row.CMI.toFixed(2) }}</span>
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="时间消耗">
          <template slot-scope="scope">
            <span
              v-bind:class="{
                red: IsRed(scope.row.时间消耗, 1),
              }"
              >{{ scope.row.时间消耗.toFixed(2) }}</span
            >
          </template>
        </el-table-column> -->

        <el-table-column label="时间消耗">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="
              比例(scope.row.床日, scope.row.病例数) +
              '/' +
              比例(scope.row.标杆床日, scope.row.病例数)
            " placement="right">
              <span v-bind:class="{
                ffred: IsRed(scope.row.床日, scope.row.标杆床日),
                ffblue: IsBlue(scope.row.床日, scope.row.标杆床),
              }">{{ 比例(scope.row.床日, scope.row.标杆床日) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column label="费用消耗">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="
              比例(scope.row.总费用, scope.row.病例数) +
              '/' +
              比例(scope.row.标杆总费用, scope.row.病例数)
            " placement="right">
              <span v-bind:class="{
                ffred: IsRed(scope.row.总费用, scope.row.标杆总费用),
                ffblue: IsBlue(scope.row.总费用, scope.row.标杆总费用),
              }">{{ 比例(scope.row.总费用, scope.row.标杆总费用) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column label="标杆来源" :formatter="标杆来源_fmt">
        </el-table-column>
      </el-table>
    </el-row>
  </div>
</template>

<script lang="ts">
import dayjs from "@/utils/dayjs.min.js";
import { Component, Vue } from "vue-property-decorator";
import { Format } from "@/utils/Utils";
import { dept } from "@/api/patient";
import { costLs } from "@/api/report";
import { UserModule } from "@/store/modules/user";
@Component({
  name: "cost-struct",
})
export default class extends Vue {
  private grp = "病组编码,病组名称";
  private query = {
    stime: "",
    etime: Format("yyyy-MM-dd", new Date()),
    s: "",
    grp: "病组编码,病组名称",
    size: "10",
    o: "病例数",
    deptValue: "",
    x: "DESC",
    order: "",
    w: "",
    t: (<any>window).MyConf["DataType"] || "出院日期",
  };

  private IsRed(v1: number, v2: number) {
    let r = (v1 / v2) * 1.0;

    if (r > 1.2) return true;

    return false;
  }
  private 标杆来源_fmt(row: any) {
    //console.log(row);
    let o: any = {
      1: "市级标杆",
      2: "本院标杆",
      3: "模板标杆",
    };
    return o[row.标杆来源];
  }
  private 比例(v1: number, v2: number, c: string) {
    let r = (v1 / v2) * 1.0;

    if (r == Infinity) {
      return "∞";
    }

    if (isNaN(r)) {
      return "";
    }
    return r.toFixed(2);
  }

  private fmt(row: any, col: any, val: any) {
    if (!val) return val;

    return val.toFixed(2);
  }
  private deptLs: Array<any> = [];

  public async dept() {
    let curDate = new Date();
    let t = `${Format("yyyyMMddh", curDate)}${parseInt(
      curDate.getMinutes() / 5 + ""
    )}`;
    let d: any = await dept({ t: t });
    d = d.data || [];
    let userdepts = await UserModule.GetUsername2depts();
    this.deptLs = [];
    if (userdepts.length > 0) {
      d = userdepts;
      this.query.deptValue = userdepts[0]
    } else {
      this.deptLs.push({ text: "所有科室", value: "" })
    }

    this.deptLs.push(...d.map((it: any) => ({ text: it, value: it })))

  }

  private search(e) {
    this.costLs(e);
  }

  private getSummaries(param: any) {
    const { columns, data } = param;
    const sums: any = [];

    if (this.grpIndex == 0 || !data || data.length == 0) return sums;

    let r = data[data.length - 1];

    columns.forEach((c: any, i: number) => {
      let col = c.label;

      if (i == 0) {
        sums[i] = "标杆";
        return;
      }

      if (col == "费用消耗") return;

      col = col.replace(/平均|消耗/gi, "");
      let vs = Object.keys(r).filter(
        (it) => it.indexOf(col) > -1 && it.startsWith("标杆")
      );
      if (vs.length > 0) {
        sums[i] = ((r[vs[0]] / r.病例数) * 1.0).toFixed(2);
      }
    });

    return sums;
  }
  private async created() {
    let cDate = new Date();
    let m =
      cDate.getMonth() - parseInt((<any>window).MyConf["TIMEINTERVAL"] || "1");
    cDate.setMonth(m);
    // this.query.stime = Format("yyyy-MM-dd", cDate);
    this.query.stime = dayjs().subtract(3, "month").format("YYYY-MM-DD");

    this.cols = this.grps[this.grpIndex].split(",");
    this.grpChange();

    await this.dept();

    this.costLs(null);
  }

  private ls: Array<any> = [];

  private cols: Array<any> = this.grp.split(",");

  private searchText = "";
  private grpChange() {
    this.searchText = this.grp
      .split(",")
      .map((it: string) => `${it}`)
      .join("、");
  }

  private isLoading: boolean = true;
  private async costLs(e) {
    this.isLoading = true;

    // if (!this.grp || this.grp.length == 0) return;

    this.query.grp = this.grp;

    this.query.order = `${this.query.o} ${this.query.x}`;

    if (!this.query.w) this.query.w = "1=1";

    this.query.w = this.query.w.replace(/AND \(.*\)/gi, "");

    // //分组编码不能为空

    if (this.query.w.indexOf("病组编码") < 0) {
      this.query.w = "病组编码 IS NOT NULL AND " + this.query.w;
    }
    if (this.query.s) {
      // let p = this.cols
      //   .map((it: any) => `${it} like '${this.query.s}'`)
      //   .join(" OR ");
      this.query.w += ` AND (病组编码 like '%${this.query.s}%' or 病组名称 like '%${this.query.s}%')`;
    }
    // if (this.query.deptValue) {
    // this.query.w += ` AND 科室='${this.query.deptValue}'`;
    // }

    let q = JSON.parse(JSON.stringify(this.query));
    if (q.deptValue) {
      q.w += ` AND 科室='${q.deptValue}'`;
    }
    q.grp += ",标杆来源";
    q.stime = q.stime + " 00:00:00";
    q.etime = q.etime + " 23:59:59";
    if (e) {
      q.标杆来源 = e;
    }

    let d: any = await costLs(q);
    d = d.data;
    this.ls = d;
    this.isLoading = false;
  }

  private grps: Array<any> = [
    "病组编码,病组名称",
    "科室,医生",
    "病人ID,住院号,病人姓名,主要诊断编码,主要诊断名称",
  ];

  private grpIndex = 0;

  private goBack() {
    let i = --this.grpIndex;

    if (i <= 0) {
      this.query.w = "";
      this.grp = this.grps[0];
      this.navText = "";

      this.cols = this.grps[this.grpIndex].split(",");
      this.search(null);
    } else {
      this.row_dblclick(this.rowstack[i], false);
    }
    //console.log(this.rowstack[i]);
    //this.row_dblclick(this.rowstack[]);
  }
  private rowstack: any = {};

  private navText: string = "";

  private row_dblclick(row: any, f = true) {
    if (this.grps.length <= this.grpIndex + 1) {
      this.$router.push({
        path: "/clinicalpathway/evaluate2",
        query: { id: row.病人ID, source: row.标杆来源 },
      });
      return;
    }
    if (f) this.grpIndex++;

    this.rowstack[this.grpIndex] = row;
    let ws = [];
    for (let i = this.grpIndex; i >= 0; i--) {
      ws.push(...this.grps[i].split(","));
    }

    this.query.w = ws
      .filter((it: any) => row[it])
      .map((it: any) => `${it}='${row[it]}'`)
      .join(" AND ");
    this.grp = ws.join(",");

    this.navText = ws
      .filter((it: any) => row[it])
      .map((it: any) => `${it}：${row[it]}`)
      .join("，");

    this.cols = this.grps[this.grpIndex].split(",");
    this.search(row.标杆来源);
  }

  private IsBlue(v1: number, v2: number) {
    let r = (v1 / v2) * 1.0;

    if (r < 0.8) return true;

    return false;
  }
}
</script>

<style lang="scss" scope>
.ffred {
  color: red;
  background-color: none !important;
}

.ffblue {
  color: blue;
  background-color: none !important;
}
</style>
